﻿using IdentityModel;
using Microsoft.AspNetCore.Mvc.Filters;
using Model;
using Utility.Encryption;

namespace LDM.Framework.JwtBearer.Filters
{
    public class AsyncSessionFilter : IAsyncActionFilter
    {
        private readonly Session _session;

        public AsyncSessionFilter(Session session)
        {
            _session = session;
        }

        public async Task OnActionExecutionAsync(
          ActionExecutingContext context,
          ActionExecutionDelegate next)
        {
            var user = context.HttpContext.User;
            if (user != null)
            {
                var userId = (user.FindFirst(JwtClaimTypes.Id)?.Value) ?? string.Empty;
                if (!string.IsNullOrWhiteSpace(userId))
                {
                    _session.UserId = userId.DecryptWithUrlDecode<int>();
                }
                _session.UserName = (user.FindFirst(JwtClaimTypes.Name)?.Value) ?? string.Empty;
                int.TryParse(((user.FindFirst(JwtClaimTypes.ClientId)?.Value) ?? string.Empty), out int userChannel);
                _session.UserChannel = userChannel;
            }
            await next();
        }
        
    }
}
